package cn.xn.hrms.domain.utils;

import com.alibaba.fastjson.JSON;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

/**
 *
 * 七牛云帮助类
 *
 * @author: ysz
 * @date: 2023/08/30
 **/
@Component
@Slf4j
@Data
public class QiniuUtils {

    @Value("${qiniu.accessKey}")
    private String accessKey;

    @Value("${qiniu.secretKey}")
    private String secretKey;

    @Value("${qiniu.url}")
    private String url;

    @Value("${qiniu.bucketName}")
    private String bucket;


    /**
     *
     * 上传文件到七牛云
     * @param multipartFile
     * @param fileName
     * @return
     */
    public boolean upload(MultipartFile multipartFile,String fileName) {

        Configuration configuration = new Configuration(Region.huadongZheJiang2());
        UploadManager uploadManager = new UploadManager(configuration);

        try {

            byte[] bytes = multipartFile.getBytes();
            Auth auth = Auth.create(accessKey, secretKey);
            String token = auth.uploadToken(bucket);
            Response resp = uploadManager.put(bytes, fileName, token);
            DefaultPutRet defaultPutRet = JSON.parseObject(resp.bodyString(), DefaultPutRet.class);
            log.info("upload file success,resp:{}", JSON.toJSONString(defaultPutRet));
            return true;
        } catch (Exception e) {
            log.error("upload file exception:{}", e.getMessage());
        }

        return false;
    }


}
